package DirDataAPI

import (
	"fmt"
	"io"
	"io/ioutil"
	"time"
)

/*
	高速缓存文件结构定义
*/
type TheCacheFile struct {
	Suicide     int64  //生存周期
	filePointer []byte //文件指针
}

var Interrupt chan int
var FileBuffer map[string]TheCacheFile

/*
	初始化函数
*/
func init() {
	Interrupt = make(chan int)
	FileBuffer = make(map[string]TheCacheFile)
	go func() {
		for {
			Interrupt <- 0
			// 删除缓存放到线程里执行
			TheCurrentTime := time.Now().Unix()
			for key, member := range FileBuffer {
				if TheCurrentTime-member.Suicide > 240 {
					delete(FileBuffer, key)
					fmt.Print("删除缓存: " + key + "\n")
				}
			}
		}
	}()
}

/*
	读取文件数据发送到前端
*/
func SendFile(w io.Writer, Directory string, file string) {
	// 查询缓存
	Data, ok := FileBuffer[file]
	if ok {
		// 修改缓存周期
		Data.Suicide = time.Now().Unix()
		// 发送数据
		w.Write(Data.filePointer)
		// 清理缓存
		<-Interrupt
	} else {
		// 添加通道
		filePointer := make(chan []byte)
		defer close(filePointer)
		// 添加缓存到队列
		go func() {
			// 创建缓存
			FileData, err := ioutil.ReadFile(Directory + file)
			if err != nil {
				filePointer <- []byte("文件不存在")
				return
			} else {
				fmt.Print("创建缓存: " + file + "\n")
				filePointer <- FileData
				FileBuffer[file] = TheCacheFile{
					Suicide:     time.Now().Unix(),
					filePointer: FileData,
				}
			}
		}()
		w.Write(<-filePointer)
	}
}
